<?php
/**
 * Introduction: 支付
 * @author: 杨陈鹏
 * @date: 2016/4/7 23:00
 * @email: yangchenpeng@cdlinglu.com
 */

namespace WeChat\Controller\Pay;


use Common\Controller\WeChat\SignController;
use Think\Wxpay\Wxpay;

class IndexController extends SignController
{
    /**
     * Introduction: 支付
     * @author: 杨陈鹏
     * @date: 2016/4/7 23:00
     * @email: yangchenpeng@cdlinglu.com
     */
    public function index()
    {


        $order_id = I('param.order_id');

        $balanced = I('param.balanced');

        $code = I('param.code');

        $order_logic = D('Common/Order','Logic');

        if(!$order_id)
            outPut(['code' => 300,'msg' => '缺少订单信息!']);

        if(!$code)
            outPut(['code' => 300,'msg' => '缺少code!']);

        //检测库存
        $check = $order_logic::checkStorage($order_id);

        if($check['code'] == 300)
            outPut($check);
        //检测订单中是否有已经下架的商品,如果有,则更改订单状态

        $check_goods_state = $order_logic::checkGoodsState($order_id);

        if($check_goods_state['code'] == 300)
            outPut($check_goods_state,true);


        $order = $order_logic::calcOrderTotalPrice($order_id);

        $order_info['order_sn']                 = $order['data']['number'];
        $order_info['buyer_name']               = '您在'.C('SMS_CONFIG.SMS_API_SIGN').'的交易订单号为:'.$order['data']['number'].'。交易时间:'.date('Y-m-d H:i:s');
        $order_info['order_amount']               = intval($order['data']['total']);



        $use = 0;

        $member_logic = D('Common/Member','Logic');

        //解冻当前订单中的资金,以防多次提交支付而多次冻结账户余额
        $balance_pay_nums = $order_logic::$model
            ->where(['id' => $order_id])
            ->getField('balance_pay_nums');

        $member_logic::$model
            ->where(['uid' => self::$uid])
            ->setDec('frozen',$balance_pay_nums);

        //是否余额优先支付
        if($balanced === 'yes'){


            //获取当前用户账户信息
            $balance = $member_logic::$model
                ->where(['uid' => self::$uid])
                ->field('balance,frozen')
                ->find();

            //获取可以余额
            $use = intval($balance['balance']) - intval($balance['frozen']);

            //如果余额大于订单的支付余额,则直接支付成功
            if( $use >=  intval($order['data']['total'])){

                if($this->_pay($order['data']))
                {

                    //减去当前用户余额
                    $member_logic::$model
                        ->where(['uid' => self::$uid])
                        ->setDec('balance',$order['data']['total']);

                    outPut(['code' => 200,'msg' => '支付成功!' ,'data' => ['isOrderFinish' => true]]);

                } else {

                    outPut(['code' => 300, 'msg' => '支付失败']);

                }

            } else {

                //剩余的使用第三方支付
                $order['data']['total'] -= $use;

            }


        }
        //冻结资金
        $member_logic::$model
            ->where(['uid' => self::$uid])
            ->setInc('frozen',$use);

        //记录到当前订单当中
        $order_logic::$model
            ->where(['id' => $order_id])
            ->save(['balance_pay_nums' => $use,'third_pay_nums' => intval($order['data']['total'])]);


        $order_info['order_amount'] = $order['data']['total'];


        $pay = new \Think\Wxpay\Wxpay();

        outPut($pay->WeChatPay($order_info,$code));

    }

    private function _pay($order_info)
    {

        //组装订单信息
        $order_data['pay_type'] = 3;
        //$order_data['third_number'] = $data['trade_no'];
        //$order_data['third_accounts'] = $data['buyer_email'];
        //$order_data['third_use_account'] = $data['buyer_id'];
        //$order_data['third_use_account'] = 2;
        $order_data['pay_time'] = NOW_TIME;
        $order_data['status'] = 2;

        $member_consumption['description'] = '(余额支付)';
        $member_consumption['time'] = NOW_TIME;
        $member_consumption['nums'] = $order_info['total'];//$data['total_fee'] * 100;


        $order_logic = D('Common/Order','Logic');

        //商品增加销量和减去库存
        $order_logic::success(['number' => $order_info['number']]);
        try{


            $model = M();

            //开启事物

            $model->startTrans();

            $member_consumption['uid'] = $model
                ->table( '__ORDER__' )
                ->where( [['number' => $order_info['number']]] )
                ->getField( 'uid' );

            //修改订单状态
            $res_order = $model
                ->table( '__ORDER__' )
                ->where( ['number' => $order_info['number']] )
                ->save($order_data);


            $res_member_consumption = $model
                ->table('__MEMBER_CONSUMPTION_RECORD__')
                ->add($member_consumption);



            //处理分销逻辑代码实现





            if ( $res_order && $res_member_consumption ){
                //提交事物
                $model->commit();



                return true;
            }

            //事物回滚
            $model->rollback();

            return false;

        } catch (\Exception $e){

            file_put_contents(LOG_PATH.'balancepay_callback_error_'.$order_info['number'].'.log',$e->getMessage());

        }

    }

}